﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using sdamarketing.App_Code;

namespace sdamarketing.Administration
{
    public partial class AddUser : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (Session["iduser"] == null || Session["username"] == null)
                    {
                        Response.Redirect("~/Default.aspx");
                    }
                    else
                    {
                        if (RolesAndPrivileges.AuthenticateUserWithPanel("Додади корисник", Int32.Parse(Session["idRole"].ToString())) == 0)
                        {
                            Response.Redirect("~/Home.aspx");
                        }
                    }
                    /*
                                    if (RolesAndPrivileges.AuthenticateUserWithPanel(2,Int32.Parse(Session["idRole"].ToString())) == 0)
                                    {
                                        Response.Redirect("~/Home.aspx");
                                    }
                    */
                    DataSet roles = ReturnDataSet.ReturSet("select name, idRole FROM Roles");
                    PrivilegesDropDownList.DataValueField = "idRole";
                    PrivilegesDropDownList.DataTextField = "name";
                    PrivilegesDropDownList.DataSource = roles;
                    PrivilegesDropDownList.DataBind();
                    PrivilegesDropDownList.Items.Insert(0, new ListItem("", ""));
                    PrivilegesDropDownList.ClearSelection();

                    DataSet Sex = ReturnDataSet.ReturSet("SELECT idSex, sex FROM Sex");
                    DropDownListSex.DataValueField = "idSex";
                    DropDownListSex.DataTextField = "sex";
                    DropDownListSex.DataSource = Sex;
                    DropDownListSex.DataBind();
                    DropDownListSex.Items.Insert(0, new ListItem("", ""));

                    DataSet Age = ReturnDataSet.ReturSet("SELECT idAge, fromAndTo FROM Age");
                    DropDownListAge.DataValueField = "idAge";
                    DropDownListAge.DataTextField = "fromAndTo";
                    DropDownListAge.DataSource = Age;
                    DropDownListAge.DataBind();
                    DropDownListAge.Items.Insert(0, new ListItem("", ""));

                    DataSet Education = ReturnDataSet.ReturSet("SELECT idEducation, education FROM Educations");
                    DropDownListEducation.DataValueField = "idEducation";
                    DropDownListEducation.DataTextField = "education";
                    DropDownListEducation.DataSource = Education;
                    DropDownListEducation.DataBind();
                    DropDownListEducation.Items.Insert(0, new ListItem("", ""));

                    DataSet Status = ReturnDataSet.ReturSet("SELECT idSocialStructure, status FROM SocialStructures");
                    DropDownListStructure.DataValueField = "idSocialStructure";
                    DropDownListStructure.DataTextField = "status";
                    DropDownListStructure.DataSource = Status;
                    DropDownListStructure.DataBind();
                    DropDownListStructure.Items.Insert(0, new ListItem("", ""));
                   
                    DataSet Nacionalost = ReturnDataSet.ReturSet("SELECT idNacionalnost,Nacionalnost FROM Nationality");
                    DropDownListNationality.DataValueField = "idNacionalnost";
                    DropDownListNationality.DataTextField = "Nacionalnost";
                    DropDownListNationality.DataSource = Nacionalost;
                    DropDownListNationality.DataBind();
                    DropDownListNationality.Items.Insert(0, new ListItem("", ""));

                    DataSet Regions = ReturnDataSet.ReturSet("SELECT idRegion,region FROM Regions");
                    DropDownListRegion.DataValueField = "idRegion";
                    DropDownListRegion.DataTextField = "region";
                    DropDownListRegion.DataSource = Regions;
                    DropDownListRegion.DataBind();
                    DropDownListRegion.Items.Insert(0, new ListItem("", ""));

                    DataSet Locality = ReturnDataSet.ReturSet("SELECT idLocality,locality FROM Localitys");
                    DropDownListLocality.DataValueField = "idLocality";
                    DropDownListLocality.DataTextField = "locality";
                    DropDownListLocality.DataSource = Locality;
                    DropDownListLocality.DataBind();
                    DropDownListLocality.Items.Insert(0, new ListItem("", ""));

                    DataSet Income = ReturnDataSet.ReturSet("SELECT idIncome,opisIncome FROM Income");
                    DropDownListIncome.DataValueField = "idIncome";
                    DropDownListIncome.DataTextField = "opisIncome";
                    DropDownListIncome.DataSource = Income;
                    DropDownListIncome.DataBind();
                    DropDownListIncome.Items.Insert(0, new ListItem("", ""));
                }
                catch (Exception exception)
                {
                    SendToLogFile.SendRecordToFIle(DateTime.Now.ToString() + " -exc- " + exception.Message.ToString() + " -stackTrace- " + exception.StackTrace.ToString() + " -addProgram- ");
                }
            }
        }

        protected void saveButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (Users.FindUser(UsernameTextBox.Text.ToString()) == 0)
                {
                    String appPath = Request.PhysicalApplicationPath;
                    String userName = UsernameTextBox.Text;
                    String saveDir = @"\Uploads\" + userName + "\\";
                    String savePicPath = @"\Uploads\" + userName + "\\";

                    System.IO.Directory.CreateDirectory(appPath + "Uploads\\" + userName);

                    //Dodadi korisnik
                    Users.AddUser(FirstNameTextBox.Text, LastNameTextBox.Text, UsernameTextBox.Text, PasswordTextBox.Text, EMailTextBox.Text, QuestionTextBox.Text, AnswerTextBox.Text, 2, Int32.Parse(DropDownListSex.SelectedValue.ToString()), Int32.Parse(DropDownListEducation.SelectedValue.ToString()), Int32.Parse(DropDownListStructure.SelectedValue.ToString()), Int32.Parse(DropDownListAge.SelectedValue.ToString()), Int32.Parse(DropDownListNationality.SelectedValue.ToString()), Int32.Parse(DropDownListRegion.SelectedValue.ToString()), Int32.Parse(DropDownListLocality.SelectedValue.ToString()), Int32.Parse(DropDownListIncome.SelectedValue.ToString()), savePicPath);
                    
                    if (Session["MyCulture"].ToString() == "en-US")
                    {
                        lblMessage.Text = "User added.";
                    }
                    else
                    {
                        lblMessage.Text = "Корисникот е успешно додаден";
                    }
                    if (FileUpload1.HasFile)
                    {
                        String fileName = Server.HtmlEncode(FileUpload1.FileName);
                        String extension = System.IO.Path.GetExtension(fileName);
                        int fileSize = FileUpload1.PostedFile.ContentLength;

                        if (fileSize < 2100000 && ((extension.ToUpper() == ".JPG") | (extension.ToUpper() == ".JPEG")))
                        {
                            String savePath = appPath + saveDir + "profilePIC.jpg";
                            FileUpload1.SaveAs(savePath);
                            ImageManipulator.ResizeImage(savePath, savePath, 120, 120, false);
                            lblStatusUpload.Text = "Your file was uploaded successfully.";
                        }
                        else
                        {
                            lblStatusUpload.Text = "Your file was not uploaded because " +
                                          "it exceeds the 2 MB size limit OR it does not have a .jpg or .jpeg extension.";
                        }
                    }
                    else
                    {
                        lblStatusUpload.Text = "You did not specify a file to upload.";
                    }
                    
                  //if (Users.FindUser(FirstNameTextBox.Text) != 0)
                  //{
                      SaveHistory.addHystoriForUser(Int32.Parse(Session["idUser"].ToString()), Users.FindUser(UsernameTextBox.Text), 1);
                  //}
                    int ajdiNaUser = Users.FindUser(UsernameTextBox.Text);
                    FirstNameTextBox.Text = "";
                    LastNameTextBox.Text = "";
                    UsernameTextBox.Text = "";
                    EMailTextBox.Text = "";
                    QuestionTextBox.Text = "";
                    AnswerTextBox.Text = "";
                    PrivilegesDropDownList.ClearSelection();
                    DropDownListSex.ClearSelection();
                    DropDownListAge.ClearSelection();
                    DropDownListEducation.ClearSelection();
                    DropDownListStructure.ClearSelection();
                    DropDownListNationality.ClearSelection();
                    DropDownListIncome.ClearSelection();
                    if (Session["MyCulture"].ToString() == "en-US")
                    {
                        lblMessage.Text = "User added.";
                    }
                    else
                    {
                        lblMessage.Text = "Корисникот е успешно додаден";
                    }

                    
                    Zainteresiranost.AddInteresi(1, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(2, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(3, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(4, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(5, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(6, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(7, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(8, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(9, 0, ajdiNaUser);
                    Zainteresiranost.AddInteresi(10,0, ajdiNaUser);
                }
                else
                {
                    if (Session["MyCulture"].ToString() == "en-US")
                    {
                        lblMessage.Text = "Username already in use";
                    }
                    else
                    {
                        lblMessage.Text = "Корисникот со такво корисничко име веќе постои";
                    }
                   
                }
            }
            catch (SqlException exception)
            {

                if (Session["MyCulture"].ToString() == "en-US")
                {
                    lblMessage.Text = "Error , try again";
                }
                else
                {
                    lblMessage.Text = "Грешка обиди се повторно";
                }
                 //SendToLogFile.SendRecordToFIle(DateTime.Now.ToString() + " -exc- " + exception.Message.ToString() + " -stackTrace- " + exception.StackTrace.ToString() + " -addUser- ");
            }
        }
    }
}
